
class StudentInfo:
    #学生编号 id_no,姓名 name,性别 sex,年龄 age,班级 cls,地址 addr
    def __init__(self, **kwargs):
        print("------------------初始化 ScoreInfo-----------")
        self.id_no = kwargs.get("id_no")
        self.name = kwargs.get("name")
        self.sex = kwargs.get("sex")
        self.age = kwargs.get("age")
        self.cls = kwargs.get("cls")
        self.addr = kwargs.get("addr")



    '''把对象字典转换成csv行字符串:9001,张飞,男,19,科创一班,深圳南山一路'''
    @classmethod
    def dict_to_csv_row(cls, dict_obj):
        return f"{dict_obj['id_no']},{dict_obj['name']},{dict_obj['sex']},{dict_obj['age']},{dict_obj['cls']},{dict_obj['addr']}\n"

    '''文件读取csv内容，转换字典列表'''
    @classmethod
    def read_student_data(cls):
        with open("student_data.csv", "r", encoding="utf-8") as f:
            lines = f.readlines()
            student_data = []
            for line in lines:
                cols = line.strip().split(",")
                #转换成对象
                student_info = StudentInfo(id_no=int(cols[0]), name=cols[1], sex=cols[2], age=int(cols[3]), cls=cols[4], addr=cols[5])
                student_data.append(student_info.__dict__)
            return student_data



    '''写入csv文件,内存数据写入文件'''
    @classmethod
    def write_student_data(cls, data):
        # 写入文件
        with open("student_data.csv", "w", encoding="utf-8") as f:
            for item in data:
                #转换成csv格式，写入文件
                f.write(cls.dict_to_csv_row(item))






'''测试代码'''
if __name__ == "__main__":
    student_info = StudentInfo(id_no=9001, name="张飞", sex="男", age=19, cls="科创一班", addr="深圳南山一路")
    print(student_info)
    print(student_info.dict_to_csv_row(student_info.__dict__))